<?php
namespace app\index\controller;
use app\common\controller\Base;
use app\common\model\Clinic;
use app\common\model\ClinicConfig;
use app\common\model\ClinicDictsheet; //字典表数据
use app\index\library\Auth;
use think\facade\Url;

/*
* 前台控制器基类
*/
class BaseIndex extends Base
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = [];  //无需鉴权的方法，但需要登录
	protected $auth = null;
	
	protected $admin = [];  //当前登录的管理员信息
	protected $adminMenuList = [];  //当前登录的管理员功能菜单
	protected $clinic = [];  //当前登录的诊所信息
	protected $clinicMall = [];  //当前登录的诊所【总店】信息
	protected $zsConfig = [];  //当前登录的【诊所配置】信息
	protected $zsMallConfig = [];  //当前登录的诊所【总店】配置信息

    //初始化
    public function initialize()
    {
        parent::initialize();
		//登录授权
		$this->auth = Auth::instance();
		//设置当前配置参数
		$this->auth->setAuthWebConfig($this->site);
		//用户登录信息
	    $this->admin = $this->auth->getAdminInfo();
		//检测是否需要验证登录
		if(!$this->auth->match($this->noNeedLogin))
		{
			//检测是否登录
			if (!$this->admin)
			{
				$currAction = strtolower($this->request->action());
				if($currAction != 'logout' && $currAction != 'login')
				{
					$backUrl = $this->request->url(true);
					$loginUrl = Url::build('index/index/login') . '?backurl=' . urlencode($backUrl);
					if($this->request->isAjax())
					{
						die(json_encode(['err' => '1', 'msg' => '登录超时，请退出重新登录。']));
					}else{
						return $this->redirect($loginUrl, '', 302);
					}
				}else{
					if($this->request->isAjax())
					{
						die(json_encode(['err' => '1', 'msg' => '登录超时，请退出重新登录。'],JSON_UNESCAPED_UNICODE));
					}else{
						return $this->redirect(Url::build('index/index/login'), '', 302);
					}
				}
			}else{ //用户已登录
				//当前管理人员的所有节点 url
                $this->admin['all_rules_list'] = $this->auth->getAdminAllRulesList($this->admin);
				//当前用户登录的诊所信息
				$this->clinic = $this->admin['clinic_info'];
				$this->zsConfig = ClinicConfig::getClinicSystemConfig($this->admin['clinic_id']);
				//当前诊所 总店信息
				if(isset($this->clinic['mall_id']) && intval($this->clinic['mall_id']) > 0)
				{
					//当前登录的诊所【总店】信息
					$this->clinicMall = Clinic::getClinicInfo($this->clinic['mall_id']);
					//当前登录的诊所【总店】配置信息
					$this->zsMallConfig = ClinicConfig::getClinicSystemConfig($this->clinic['mall_id']);
				}
				//当前登录的管理员功能菜单
				$this->adminMenuList = $this->auth->getAdminMenu($this->admin,$this->clinic);
			}
			//权限验证
			if(!$this->auth->match($this->noNeedRight))
			{
				if(!$this->auth->ruleCheck($this->currRouteUrl,$this->admin))
				{
					if($this->request->isAjax())
					{
						die(json_encode(['err' => '1', 'msg' => '对不起，操作未授权！'],JSON_UNESCAPED_UNICODE));
					}else{
						$turnPage = !$this->admin['index_page'] ? Url::build('index/index/logout') : Url::build($this->admin['index_page']);
						return $this->error('对不起，操作未授权！', $turnPage);
					}
				}
			}
		}
		
		if(!$this->request->isAjax())
		{
			$this->assign([
				'admin' => $this->admin, //当前登录的管理员信息
				'menu_list' => $this->adminMenuList, //当前登录的管理员功能菜单
				'clinic' => $this->clinic, //当前登录的诊所信息
				'zs_config' => $this->zsConfig, //当前登录的【诊所配置】信息
				'clinic_mall' => $this->clinicMall, //当前登录的诊所【总店】信息
				'zs_mall_config' => $this->zsMallConfig, //当前登录的诊所【总店】配置信息
			]);	
		}
		
    }




    /*
    * 通用移动加权平均法 单价
    * $beforeMoney = 之前金额,$beforeNum = 之前数量,$afterMoney = 现在金额,$afterNum = 现在数量
    * return 新的成本单价
    */
    public function getPublickArgCostPrice($beforeMoney = 0,$beforeNum = 0,$afterMoney = 0,$afterNum = 0)
    {
		//原库存为负数时
		if($beforeNum <= 0) $beforeNum = 0;
		//移动加权平均法 公式：(原成本 x 原库存 + 新成本 x 新入数量)÷总库存数（新+原）= 新成本
		//1.原成本 x 原库存
		$r1 = bcmul((float)$beforeMoney,(int)$beforeNum,2);
		//2.新成本 x 新入数量
		$r2 = bcmul((float)$afterMoney,(int)$afterNum,2);
		//3.(原成本 x 原库存 + 新成本 x 新入数量)
		$r3 = bcadd(abs($r1),$r2,2);
		//总库存数（新+原）
		$zongKc = bcadd((int)$beforeNum,(int)$afterNum,0);
		if($zongKc <= 0) return __formatNumber($afterMoney);
		return _formatNumber(round(bcdiv($r3,(int)$zongKc,3),2)); //÷总库存数（新+原）= 新成本
    }
    //获取当前管理人员姓名
    public function getThisAdminName($admin = [])
    {
    	if(isset($admin['nickname']) && $admin['nickname']) return trim($admin['nickname']);
    	if(isset($admin['user_name']) && $admin['user_name']) return trim($admin['user_name']);
    	if(isset($admin['user_mobile']) && $admin['user_mobile']) return trim($admin['user_mobile']);
    	return '';
    }
    /**
    *检测表中字段是否唯一 return true = 存在， false = 不存在
    */
    public function checkUniqueCode($num = '', $fields = 'entry_sn', $tableName = 'clinic_entry')
    {
        if(!$num || !$fields || !$tableName) return false;
        $id = (int)ClinicDictsheet::getSplitDb($this->admin['clinic_id'],$tableName)->where([$fields => trim($num)])->count();
        return intval($id) > 0 ? true : false;
    }
    //日期格式条件拆分 2020-09-03 - 2020-10-28
    public function getWhereDate($date = '')
    { 
        if(!$date) return false;
        list($s1, $s2) = explode(' - ', trim($date));
        if(!$s1 || !$s2) return false;
        return [strtotime($s1 . ' 00:00:00'),strtotime($s2 . ' 23:59:59')];
    }
    //日期格式条件拆分为时间戳格式，详细到时分秒   return [160000000000,1600000000]
    public function getWhereDateTime($date = '')
    {
        if(!$date) return false;
        list($s1, $s2) = explode(' - ', trim($date));
        if(!$s1 || !$s2) return false;
        return [strtotime($s1),strtotime($s2)];
    }
    /**
    *入库的项目类型判断
    *项目类型xy=西药,zcy=中成药,zyyp=中药饮片,zykl=中药颗粒,cl=材料
    */
    public function getXmType($arr = [])
    {
        //类型,0=西药,1=中药,2=材料
        if(isset($arr['drugs_type']) && $arr['drugs_type'] == 0)
        {
            if(isset($arr['yp_type']) && $arr['yp_type'] == 0) return 'xy';
            if(isset($arr['yp_type']) && $arr['yp_type'] == 1) return 'zcy';
        }
        //1=中药
        if(isset($arr['drugs_type']) && $arr['drugs_type'] == 1)
        {
            if(isset($arr['yp_type']) && $arr['yp_type'] == 0) return 'zyyp';
            if(isset($arr['yp_type']) && $arr['yp_type'] == 1) return 'zykl';
        }
        //2=材料
        if(isset($arr['drugs_type']) && $arr['drugs_type'] == 2)
        {
            return 'cl';
        }
        return '';
    }

}
